import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'log_util.dart';
import 'text_style.dart';

import 'color.dart';

typedef OnSelectedDate = void Function(String date);
typedef OnCleanDate = void Function(String date);

//年-月-日 时:分  时间选择器
class DateTimePickers extends StatefulWidget {
  DateTimePickers(
      {this.title,
      this.onSelectedDate,
      this.type = false,
      this.onCleanDate,
      this.selectedDate,
      this.startYear = 2020,
      this.endYear = 2100});

  // 结果返回
  final OnSelectedDate? onSelectedDate;
  final OnCleanDate? onCleanDate;
  final DateTime? selectedDate; //选中的时间
  final int startYear;
  final int endYear;
  final String? title;
  final bool type;

  @override
  _DateTimePickersState createState() => _DateTimePickersState();
}

class _DateTimePickersState extends State<DateTimePickers> {
  //年数组
  List<String>? yearList = [];

  //月数组
  List<String>? monthList = [];

  //天数组
  List<String>? dayList = [];

  List<String>? hourList = [];
  List<String>? minuteList = [];

  //年的索引
  late int yearIndex;

  //月的索引
  late int monthIndex;

  //天的索引
  late int dayIndex;

  //时的索引
  late int hourIndex;

  //分的索引
  late int minuteIndex;

  //每列的宽度
  double? _columnWidth;

  FixedExtentScrollController? yearScrollController;
  FixedExtentScrollController? monthScrollController;
  FixedExtentScrollController? dayScrollController;
  FixedExtentScrollController? hourScrollController;
  FixedExtentScrollController? minuteScrollController;

  @override
  void initState() {
    super.initState();

    _columnWidth = ScreenUtil().screenWidth / 5;

    _setupData();

    _initSelectedIndex();
  }

  @override
  void dispose() {
    yearScrollController!.dispose();
    monthScrollController!.dispose();
    dayScrollController!.dispose();
    hourScrollController!.dispose();
    minuteScrollController!.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
      child: Container(
        color: ColorManager.colorFFFFFF,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            _headerWidget(),_datePicker()
            // Expanded(child: ,)

          ],
        ),
      ),
    );
  }

  ///初始化数据
  void _setupData() {
    for (int i = widget.startYear; i <= widget.endYear; i++) {
      yearList!.add(i.toString());
    }

    for (int i = 1; i <= 12; i++) {
      monthList!.add(i.toString());
    }

    for (int i = 0; i <= 23; i++) {
      hourList!.add(i.toString());
    }

    for (int i = 0; i <= 59; i++) {
      minuteList!.add(i.toString());
    }
    // 初始化天数(当前时间系统时间的天数)
    int year = DateTime.now().year;
    int month;
    if (widget.selectedDate == null) {
      month = DateTime.now().month;
    } else {
      month = widget.selectedDate!.month;
    }

    dayList = _getDayList(year: year, month: month);
  }

  int _getDayCount({int? year, int? month}) {
    int dayCount = DateTime(year!, month! + 1, 0).day;
    return dayCount;
  }

  List<String> _getDayList({int? year, int? month}) {
    List<String> dayList = [];
    int days = _getDayCount(year: year, month: month);
    for (int i = 1; i <= days; i++) {
      dayList.add(i.toString());
    }

    return dayList;
  }

  ///选中年月后更新天
  void _updateDayList() {
    int? year = int.parse(yearList![yearIndex]);
    int? month = int.parse(monthList![monthIndex]);

    setState(() {
      dayList = _getDayList(year: year, month: month);
      // dayIndex=0;
      // if (dayScrollController!.positions.length > 0) {
      //   dayScrollController!.jumpTo(0);
      // }
    });
  }

  ///初始化时间索引
  void _initSelectedIndex() {
    final List uniqueYearList = Set.from(yearList!).toList();
    final List uniqueMonthList = Set.from(monthList!).toList();
    final List uniqueDayList = Set.from(dayList!).toList();
    final List uniqueHourList = Set.from(hourList!).toList();
    final List uniqueMinuteList = Set.from(minuteList!).toList();

    ///获取索引
    if (widget.selectedDate != null) {
      ///传了选中日期的时候
      setState(() {
        yearIndex =
            uniqueYearList.indexOf(widget.selectedDate!.year.toString());
        monthIndex =
            uniqueMonthList.indexOf(widget.selectedDate!.month.toString());
        dayIndex = uniqueDayList.indexOf(widget.selectedDate!.day.toString());
        hourIndex =
            uniqueHourList.indexOf(widget.selectedDate!.hour.toString());
        minuteIndex =
            uniqueMinuteList.indexOf(widget.selectedDate!.minute.toString());
      });
    } else {
      ///没有传选中日期默认当前系统时间
      setState(() {
        yearIndex = uniqueYearList.indexOf(DateTime.now().year.toString());
        monthIndex = uniqueMonthList.indexOf(DateTime.now().month.toString());
        dayIndex = uniqueDayList.indexOf(DateTime.now().day.toString());
        hourIndex = uniqueHourList.indexOf(DateTime.now().hour.toString());
        minuteIndex =
            uniqueMinuteList.indexOf(DateTime.now().minute.toString());

        LogUtils.d('${DateTime.now()}');
      });
    }

    yearScrollController = FixedExtentScrollController(initialItem: yearIndex);
    monthScrollController =
        FixedExtentScrollController(initialItem: monthIndex);
    dayScrollController = FixedExtentScrollController(initialItem: dayIndex);
    hourScrollController = FixedExtentScrollController(initialItem: hourIndex);
    minuteScrollController =
        FixedExtentScrollController(initialItem: minuteIndex);
  }

  Widget _headerWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              Navigator.pop(context);
            },
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 15.w),
              child: Text(
                '取消',
                style: TextStyleUtils.style969799(fontSize: 14.sp),
              ),
            )),
        GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              if (widget.onSelectedDate != null) {
                dayIndex = dayScrollController!.selectedItem;
                String date = yearList![yearIndex] +
                    '-' +
                    monthList![monthIndex].padLeft(2, '0') +
                    '-' +
                    dayList![dayIndex].padLeft(2, '0') +
                    " " +
                    hourList![hourIndex].padLeft(2, '0') +
                    ":" +
                    minuteList![minuteIndex].padLeft(2, '0');

                widget.onSelectedDate!(date);
              }
            },
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 15.w),
              child: Text(
                '确定',
                style: TextStyleUtils.styleF65247(fontSize: 14.sp),
              ),
            )),
      ],
    );
  }

  Widget _datePicker() {
    return Container(
      height: 330.w,
      child: Stack(
        children: [
          Row(
            children: <Widget>[
              Expanded(child: _yearPickerView()),
              Expanded(child: _monthPickerView()),
              Expanded(child: _dayPickerView()),
              Expanded(child: _hourPickerView()),
              Expanded(child: _minutePickerView()),
            ],
          ),
          Container(
            color: ColorManager.colorE5E4E3,
            margin: EdgeInsets.only(top: 144.w),
            height: 0.5.w,
          ),
          Container(
            color: ColorManager.colorE5E4E3,
            margin: EdgeInsets.only(top: 192.w),
            height: 0.5.w,
          ),
        ],
      ),
    );
  }

  ///年
  Widget _yearPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: yearScrollController,
        children: _buildYearWidget(),
        looping: false,
        selectionOverlay: const Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            yearIndex = index;
          });
          // _updateDayList();
        },
        itemExtent: 48.w,
      ),
    );
  }

  ///月
  Widget _monthPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: monthScrollController,
        children: _buildMonthWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            monthIndex = index;
          });

          _updateDayList();
        },
        itemExtent: 48.w,
      ),
    );
  }

  ///日
  Widget _dayPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: dayScrollController,
        children: _buildDayWidget(),
        selectionOverlay: const Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            dayIndex = index;
          });
        },
        itemExtent: 48.w,
      ),
    );
  }

  //小时
  Widget _hourPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: hourScrollController,
        children: _buildHourWidget(),
        selectionOverlay: const Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            hourIndex = index;
          });
        },
        itemExtent: 48.w,
      ),
    );
  }

  //分钟
  Widget _minutePickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: minuteScrollController,
        children: _buildMinuteWidget(),
        selectionOverlay: const Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            minuteIndex = index;
          });
        },
        itemExtent: 48.w,
      ),
    );
  }

  ///年Widget
  List<Widget> _buildYearWidget() {
    List<Widget> yearListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in yearList!) {
      yearListWidget.add(
        Center(
          child: Text(
            '$item年',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16.w),
            maxLines: 1,
          ),
        ),
      );
    }

    return yearListWidget;
  }

  ///月Widget
  List<Widget> _buildMonthWidget() {
    List<Widget> monthListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in monthList!) {
      monthListWidget.add(
        Center(
          child: Text(
            '$item月',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return monthListWidget;
  }

  ///日Widget
  List<Widget> _buildDayWidget() {
    List<Widget> dayListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in dayList!) {
      dayListWidget.add(
        Center(
          child: Text(
            '$item日',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return dayListWidget;
  }

  ///shiWidget
  List<Widget> _buildHourWidget() {
    List<Widget> hourListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in hourList!) {
      hourListWidget.add(
        Center(
          child: Text(
            '$item时',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return hourListWidget;
  }

  ///分Widget
  List<Widget> _buildMinuteWidget() {
    List<Widget> minuteListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in minuteList!) {
      minuteListWidget.add(
        Center(
          child: Text(
            '$item分',
            style: TextStyle(color: ColorManager.color2A2A2A, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return minuteListWidget;
  }
}
